package com.exonline.front.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebFilter("/*")
public class ExceptionFilter extends HttpFilter {

    /*// 使用Jackson库进行JSON格式的响应输出
    private ObjectMapper mapper = new ObjectMapper();

    *
     * @desc  全局异常处理过滤器，用于处理未处理的异常，并将其转换为JSON格式的响应输出
     * @param req :请求对象
     * @param resp :服务端响应
     * @param chain :过滤器链
     * @throws ServletException 如果请求处理过程中发生错误
     * @throws IOException 如果响应过程中发生I/O错误

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(req, resp);
        } catch (NullPointerException e) {
            handleException(resp, 201, "参数缺失或空指针异常", "请确认是否正确包含请求参数", e.getMessage());
        } catch (IOException e) {
            handleException(resp, 500, "输入输出异常", "读取或写入数据时出现错误，请检查网络或相关配置", e.getMessage());
        } catch (ServletException e) {
            handleException(resp, 500, "Servlet相关异常", "Servlet处理请求过程中出现问题", e.getMessage());
        } catch (RuntimeException e) {
            handleException(resp, 500, "运行时异常", "服务器运行过程中出现未知错误", e.getMessage());
        } catch (Exception e) {
            handleException(resp, 500, "服务器内部异常", "服务器内部出现未知错误，请联系管理员", e.getMessage());
        }
    }

    *
     * @desc   处理异常，将异常信息转换为JSON格式的响应输出
     * @param resp  :服务端响应
     * @param code  :异常状态码
     * @param type  :异常类型
     * @param detail  : 异常详细信息
     * @throws IOException 如果响应过程中发生I/O错误

    private void handleException(HttpServletResponse resp, int code, String type, String msg, String detail) throws IOException {
        //设置响应头，指定返回的数据类型为JSON格式
        resp.setContentType("application/json;charset=UTF-8");
        resp.setStatus(code);
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("type", type);
        map.put("msg", msg);
        map.put("data", detail);
        //将异常信息转换为JSON格式的响应输出
        mapper.writeValue(resp.getWriter(), map);
    }*/
}